package element.synt;

import ast.*;
import element.base.Synt;
import element.base.Word;

import java.util.ArrayList;
import java.util.List;

public class ConstDecl extends Synt {

    @Override
    public List<AstItem> toAsts() {
        List<AstItem> asts = new ArrayList<>();

        String dataType;

        Type type = (Type) getNodes().get(1);

        if (type.getNodes().getFirst().isSynt(ClassType.class)) {
            dataType = ((ClassType) type.getNodes().getFirst()).findFirst().getContent();
        } else if (type.getNodes().getFirst().isSynt(FuncType.class)) {
            dataType = ((FuncType) type.getNodes().getFirst()).toFormatString();
        } else {
            dataType = ((Word) type.getNodes().getFirst()).getContent();
        }

        int defCount = (getNodes().size() - 2) / 2;

        for (int i = 0; i < defCount; i++) {
            LValStatement item = new LValStatement();
            item.isConst = true;
            item.type = Statement.StatementType.DECL_STMT;
            item.assignType = LValStatement.AssignType.NORMAL;

            ConstDef _def = (ConstDef) getNodes().get(2 * i + 2);

            if (_def.getNodes().size() == 3) {
                PrimaryDataSignature ds = new PrimaryDataSignature();
                ds.type = DataSignature.DataType.PRIMARY;
                ds.dataType = dataType;
                ds.name = _def.findFirst().getContent();
                item.LVal = ds;

                ConstInitVal init = (ConstInitVal) _def.getNodes().get(2);
                item.RVal = init.toAst();
            } else {
                ComplexDataSignature ds = new ComplexDataSignature();
                ds.type = DataSignature.DataType.COMPLEX;
                ds.opType = ComplexDataSignature.operationType.ARRAY_DECL;

                PrimaryDataSignature dataIdent = new PrimaryDataSignature();
                dataIdent.type = DataSignature.DataType.PRIMARY;
                dataIdent.dataType = dataType;
                dataIdent.name = _def.findFirst().getContent();
                ds.dataOperated = dataIdent;

                ArrayLengths lengths = (ArrayLengths) _def.getNodes().get(1);

                for (AstItem astItem: lengths.toAsts()) {
                    ds.operation.add(astItem);
                }
                item.LVal = ds;

                ConstInitVal init = (ConstInitVal) _def.getNodes().get(3);
                item.RVal = init.toAst();
            }

            asts.add(item);
        }

        return asts;
    }
}
